package com.dj.mingkong.portal.biz.core.kaptcha;

import com.google.code.kaptcha.NoiseProducer;
import com.google.code.kaptcha.util.Configurable;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 验证码加噪处理
 *
 * @author zenglonghui
 * @date: 2021/12/9 15:07
 */
public class KaptchaNoise extends Configurable implements NoiseProducer {
    @Override
    public void makeNoise(BufferedImage image, float factorOne, float factorTwo, float factorThree, float factorFour) {
        Random rand = new SecureRandom();
        int width = image.getWidth();
        int height = image.getHeight();
        Graphics2D graph = (Graphics2D) image.getGraphics();
        graph.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        graph.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
        int noiseLineNum = rand.nextInt(3);
        if (noiseLineNum == 0) {
            noiseLineNum = 1;
        }
        for (int i = 0; i < noiseLineNum; i++) {
            graph.setColor(KaptchaColor.getColor());
            graph.drawLine(rand.nextInt(width), rand.nextInt(height), 10 + rand.nextInt(20), 10 + rand.nextInt(20));
        }

        graph.dispose();
    }
}
